from django import forms
from django.core.validators import RegexValidator

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
from crispy_forms.bootstrap import FieldWithButtons, StrictButton

from web.models import UserInfo


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r"^(1[3|4|5|6|7|8|9]\d{9}$", "手机号格式错误")])
    password = forms.CharField(label="密码", widget=forms.PasswordInput())
    confirm_password = forms.CharField(label="重复密码", widget=forms.PasswordInput())
    code = forms.CharField(label="手机验证码", widget=forms.TextInput())

    class Meta:
        model = UserInfo
        fields = (
            "username",
            "email",
            "password",
            "confirm_password",
            "mobile_phone",
            "code",
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # for name, field in self.fields.items():
        #     field.widget.attrs["class"] = "form-control"
        #     field.widget.attrs["placeholder"] = f"请输入{field.label}"
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                "用户注册",
                "username",
                "email",
                "password",
                "confirm_password",
                "mobile_phone",
                FieldWithButtons("code", StrictButton("发送验证信息", css_class="btn-secondary", id="id_send_sms_btn")),
            ),
            ButtonHolder(Submit("submit", "注册", css_class="btn btn-primary")),
        )
